package com.yuan.Service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.Mapper.DishFlavorMapper;
import com.yuan.Mapper.DishMapper;
import com.yuan.Mapper.SetmealDishMapper;
import com.yuan.Mapper.SetmealMapper;
import com.yuan.Service.DishService;
import com.yuan.constant.MessageConstant;
import com.yuan.constant.StatusConstant;
import com.yuan.context.BaseContext;
import com.yuan.dto.DishDTO;
import com.yuan.dto.DishPageQueryDTO;
import com.yuan.entity.Dish;
import com.yuan.entity.DishFlavor;
import com.yuan.entity.Setmeal;
import com.yuan.entity.SetmealDish;
import com.yuan.exception.DeletionNotAllowedException;
import com.yuan.result.PageResult;
import com.yuan.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {


    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();

        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);

        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();

        if (flavors != null && flavors.size() > 0) {

            flavors.forEach(flavor -> {
                flavor.setDishId(dishId);
            });
            dishFlavorMapper.insert(flavors);
        }
    }

    @Override
    public PageResult pageSelf(DishPageQueryDTO dto) {

        Integer categoryId = dto.getCategoryId();
        String name = dto.getName();
        Integer status = dto.getStatus();
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        if (categoryId != null && categoryId != 0) {
            wrapper.eq(Dish::getCategoryId, categoryId);
        }
        if (name != null && name != "") {
            wrapper.eq(Dish::getName, name);
        }
        if (status != null && status != 0) {
            wrapper.eq(Dish::getStatus, status);
        }

        Page<Dish> page = new Page<>(dto.getPage(), dto.getPageSize());

        Page<Dish> paged = page(page, wrapper);


        return new PageResult(page.getTotal(), page.getRecords());
    }

    @Override
    public void deleteIds(List<Long> ids) {
        //判断当前菜品是否能够删除---是否存在起售中的菜品？？
        for (Long id : ids) {
            Dish dish = getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //判断当前菜品是否能够删除---是否被套餐关联了？？
            LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();

            wrapper.select(SetmealDish::getSetmealId).eq(SetmealDish::getDishId, ids);

            List<Long> setmealIds = setmealDishMapper.selectList(wrapper).stream().map(SetmealDish::getDishId).collect(Collectors.toList());
            if (setmealIds != null && setmealIds.size() > 0) {
                //当前菜品被套餐关联了，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            removeByIds(ids);

            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(DishFlavor::getDishId, ids);

            dishFlavorMapper.delete(wrapper1);

        }


    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {


        Dish dish = getById(id);

        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(wrapper);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());

        //修改菜品表基本信息
        updateById(dish);
        //删除原有的口味数据
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDTO.getId());


        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDTO.getId());
        }
        dishFlavorMapper.insert(flavors);

    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = getById(id);
        dish.setStatus(status);
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        updateById(dish);

        if (status == StatusConstant.DISABLE) {
            //将包含当前菜品的套餐也停售
            LambdaQueryWrapper<SetmealDish> Wrapper = new LambdaQueryWrapper<>();
            Wrapper.eq(SetmealDish::getDishId, id);

            List<Long> setmealIds = setmealDishMapper.selectList(Wrapper).stream().map(SetmealDish::getSetmealId).toList();

            for (Long setmealId : setmealIds) {
                Setmeal setmeal = new Setmeal();
                setmeal.setId(setmealId);
                setmeal.setUpdateUser(BaseContext.getCurrentId());
                setmeal.setUpdateTime(LocalDateTime.now());
                setmeal.setStatus(status);
                setmealMapper.updateById(setmeal);
            }


        }

    }

    @Override
    public List<Dish> listSelf(Long categoryId) {
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        return list(wrapper);

    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = list(new LambdaQueryWrapper<Dish>().eq(Dish::getCategoryId, dish.getCategoryId()));


        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : dishList) {

        }



        return List.of();
    }

}
